<template>
  <el-drawer :title="title" :visible.sync="dialog" direction="rtl" :with-header="false" custom-class="box_drawer"
    size="80%" ref="drawer" :before-close="cancelForm">
    <div class="drawer_content">
      <el-form :model="form" ref="form" :rules="rules" :inline="true" :label-width="formLabelWidth">
        <div class="drawer_main">


          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-card class="card" shadow="never">
                <div slot="header">
                  <span class="tips">协同部门管理列表</span>
                  <el-button type="success" class="right" icon="el-icon-plus" @click="handleAdd(null,queryForm.warning_order_id)">新增</el-button>
                </div>
                <el-table v-loading="listLoading" ref="listTable" stripe :data="list"
                  :element-loading-text="elementLoadingText" border
                   height="calc(100vh - 500px)">
                  <template slot="empty">
                    <el-empty :image-size="200"></el-empty>
                  </template>
                  <!-- <el-table-column show-overflow-tooltip type="selection"></el-table-column> -->
                  <!-- <el-table-column
              show-overflow-tooltip
              prop="id"
              label="序号"
              align="center"
              width="80px"              
            ></el-table-column>-->

                  <el-table-column show-overflow-tooltip prop="dept_name" label="协同部门" align="center"
                    width="420px"></el-table-column>
                  <el-table-column show-overflow-tooltip prop="feedback_require" label="反馈要求" align="center"></el-table-column>

                  <el-table-column show-overflow-tooltip label="操作" width="160" align="center">
                    <template #default="{ row }">
                      <el-button plain @click="handleEdit(row,null)" type="primary" size="mini">
                        编辑
                      </el-button>
                      <el-button plain @click="handlecancel(row)" type="danger" size="mini">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination background :current-page="queryForm.pageNo" :page-size="queryForm.pageSize"
                  :layout="layout" :total="total" @size-change="handleSizeChange"
                  @current-change="handleCurrentChange2"></el-pagination>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-card class="card" shadow="never">
                <div slot="header">
                  <span class="tips">上报</span>
                </div>

                  <el-row :gutter="20">
<!--                    <el-form-item label="是否上报" prop="">-->
<!--                      <el-radio-group v-model="radio">-->
<!--                        <el-radio :label="0">否</el-radio>-->
<!--                        <el-radio :label="1">是</el-radio>-->
<!--                      </el-radio-group>-->
<!--                    </el-form-item>-->
                      <el-form-item label="上报部门"  >
                        <el-select class="main-select-tree" style="width: 100%;" ref="selectTree" v-model="form.deptName"
                                   >
                          <el-option v-for="item in deptDatas" :key="item.id"
                                     :label="item.name" :value="item.id" style="display: none;"/>
                          <el-tree class="main-select-el-tree" ref="selecteltree" :data="deptDatas"
                                   node-key="id"
                                   @node-click="handleNodeClick"
                                   highlight-current :props="defaultProps"
                                   :current-node-key="form.dept_id"
                                   :expand-on-click-node="expandOnClickNode" default-expand-all/>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="上报领导"  >
                        <el-select v-model="form.leader_id" placeholder="请选择" >
                          <el-option
                              v-for="item in options2"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>


                    <el-form-item>
                      <el-button @click="leaderNotice" type="primary" v-if="form.leader_id != '' && form.leader_id != null &&  form.leader_id != undefined">添 加</el-button>
                    </el-form-item>


                    <!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                      <el-form-item label="当前状态" prop="username">
                        <el-radio-group v-model="form.username">
                          <el-radio label="启用"></el-radio>
                          <el-radio label="关闭"></el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col> -->
                    <div class="select-meb-box" v-if="choosePerson.length > 0">
                      <h4>已选人员：</h4>
                      <!--                      <el-tag closable type="success"> 我问问 </el-tag>-->

                      <el-tag closable type="success"  v-for="item in choosePerson"
                              :key="item.id" :value="item.id" @close="closeTag(item.id)"
                      >{{item.name}}</el-tag>

                    </div>

                  </el-row>
              </el-card>
            </el-col>
          </el-row>



        </div>
      </el-form>
      <div class="drawer_footer">
<!--        <el-button @click="cancelForm" type="primary">确 认</el-button>-->
        <el-button @click="cancelForm" >关 闭</el-button>
        <!-- <el-button
          type="primary"
          @click="$refs.drawer.closeDrawer()"
          :loading="loading"
        >
          {{ loading ? '打印中 ...' : '打 印' }}
        </el-button> -->
      </div>
    </div>
    <edits ref="edits" @fetch-data="fetchData"></edits>
    <edit ref="edit" @fetch-data="fetchData"></edit>
  </el-drawer>

</template>

<script>
import Edits from './components/edits'
import Edit from './components/edit'
import { getAllChooseDept,deleteDept,getById } from '@/api/warningOrder'
import {getDeptList, getUserByDeptId} from "@/api/dept";
import {addLeader,deleteOne,getOneOrderList} from "@/api/warningOrderLeader";
export default {
  name: 'bumentlist',
  components: { Edits,Edit },
  data() {
    return {
      title: '',
      dialog: false,
      loading: false,
      isShow: true,
      isShow1: true,
      isShow2: true,
      isShow3: true,
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        warning_order_id: '',
      },
      list: null,
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      elementLoadingText: '正在加载...',
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        dept_id: '',
        deptName: '',
        leader_id: '',

      },
      rules: {
        dept_id: [{ required: true, trigger: 'blur', message: '请选择部门' },],
        leader_id: [{ required: true, trigger: 'blur', message: '请选择领导' },],
      },
      radio:0,
      deptDatas: [],
      defaultProps: {
        children: 'children',
        name: 'name'
      },
      expandOnClickNode: true,
      options2: [],
      formLabelWidth: '100px',
      timer: null,
      choosePerson: [],
    }
  },
  created() {

  },
  mounted() { },
  methods: {
    showDia(row) {
      if (!row) {
        this.title = '新增'
      } else {
        this.title = '编辑'
        console.log('row',row);
        this.form = Object.assign({}, row)
        this.queryForm.warning_order_id = row.id
      }
      this.fetchData();
      this.getDeptData();
      // if (row){
      //   if (row.leader_id != null && row.leader_id != '' && row.leader_id != undefined){
      //     this.getLeaderInfo();
      //   }
      // }
      this.form.leader_id = '';
      this.form.dept_id = '';
      this.form.deptName = '';
      this.getChooseLeader();
      this.dialog = true
    },
    close() {
      // this.$refs['form'].resetFields()
      // this.form = this.$options.data().form

      this.dialog = false
    },
    handleAdd(row,warning_order_id) {
      var tempRow = {};
      tempRow.row = row;
      tempRow.warning_order_id = warning_order_id;
      console.log(tempRow);
      this.$refs['edits'].showDia(tempRow)
    },
    handleEdit(row,warning_order_id){
      var tempRow = {};
      tempRow.row = row;
      tempRow.warning_order_id = warning_order_id;
      console.log(tempRow);
      this.$refs['edit'].showDia(tempRow)
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange2(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    handlecancel(row) {
      if (row.id) {
        this.$baseConfirm('确认进行删除吗？', null, async () => {
          const { msg } = await deleteDept(row)
          this.$baseMessage(msg, 'success')


          // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
          const totalPage = Math.ceil((this.total - 1) / this.queryForm.pageSize) // 总页数
          this.queryForm.pageNo = this.queryForm.pageNo > totalPage ? totalPage : this.queryForm.pageNo
          this.queryForm.pageNo = this.queryForm.pageNo < 1 ? 1 : this.queryForm.pageNo


          this.fetchData()
        })
      } else {

      }
    },
    save() {
      this.$baseMessage('模拟保存成功', 'success')
      this.$emit('fetch-data')
      this.close()
    },
    moreQuery() {
      this.isShow = !this.isShow
    },
    handleClose(done) {
      if (this.loading) {
        return
      }
      this.$confirm('确定要打印吗？')
        .then((_) => {
          this.loading = true
          this.timer = setTimeout(() => {
            done()
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false
            }, 400)
          }, 2000)
        })
        .catch((_) => { })
    },
    cancelForm() {
      this.loading = false
      this.dialog = false
      this.radio = 0 ;
      this.choosePerson = [];
      clearTimeout(this.timer)
    },
    async fetchData() {
      this.listLoading = true
      const { data, totalCount } = await getAllChooseDept(this.queryForm)
      console.log(data.data);
      this.list = data.data.list
      this.total = data.data.total
      setTimeout(() => {
        this.listLoading = false
      }, 300)
    },
    //获取部门树
    getDeptData() {
      getDeptList().then((res) => {
        console.log("部门data：")
        console.log(res.data)
        this.deptDatas = res.data
      })
      // const {data} = await getDeptList()
      // console.log("部门data：")
      // console.log(data)
      // this.deptDatas = data;
    },
    handleNodeClick(node) {
      console.log(node.id)
      this.$set(this.form, "dept_id", node.id);
      this.$set(this.form, "deptName", node.name);
      this.$set(this.form, "leader_id", '');
      // this.queryForm.dept_id = node.id;

      this.getUserByDeptId()
      this.$refs.selectTree.blur();
    },
    async getUserByDeptId(){
      const {data} = await getUserByDeptId(this.form.dept_id);
      var list = data;
      this.options2 = [];
      for (var i = 0 ; i < list.length ; i++){
        var x = {};
        x.value = list[i].id;
        x.label= list[i].name;
        this.options2.push(x);
      }

    },
    leaderNotice(){
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          // console.log('form',this.form);
          var list = this.options2
          var x = {};
          x.leader_id = this.form.leader_id;
          x.warning_order_id = this.queryForm.warning_order_id;
          addLeader(x).then(res => {
            if (res.code == 0){
              var z = {};
              z.id = this.form.leader_id;

              for (var i = 0; i <list.length ; i++) {
                if (list[i].value === this.form.leader_id){
                  z.name = list[i].label;
                }
              }
              var count = 0 ;
              for (var i = 0; i <this.choosePerson.length; i++) {
                if(z.id == this.choosePerson[i].id) {
                  count++;
                }
              }
              if (count == 0) {
                this.choosePerson.push(z)
                this.$baseMessage("添加成功", 'success')
              }else {
                this.$baseMessage("上报领导已选择", 'warning')
              }



            }else {
              this.$baseMessage("添加失败", 'success')
            }

          })
        }
      })
    },
    getLeaderInfo(){
      var x = {};
      x.id = this.queryForm.warning_order_id;
      getById(x).then(res => {
        console.log('res',res);
        if (res.code === 0){
          this.radio = 1 ;
          this.form.dept_id = res.data.dept
          this.getUserByDeptId();
          this.form.deptName = res.data.dept_name;
          this.form.leader_id = res.data.leader_id
        }
      })

    },
    closeTag(val){
      var x = {};
      x.leader_id = val;
      x.warning_order_id = this.queryForm.warning_order_id;
      deleteOne(x).then(res => {
        if (res.code === 0){
          var list = this.choosePerson
          var temp = -1 ;
          for (var i = 0; i < list.length; i++) {
            if (list[i].id == val){
              temp = i ;
            }
          }
          if (-1 != temp) {
            list.splice(temp,1);
          }
          this.choosePerson = list;
        }
      })
    },
    getChooseLeader(){
      var x = {};
      x.warning_order_id = this.queryForm.warning_order_id;
      getOneOrderList(x).then(res => {
        console.log('res',res);
        if (res.code === 0){
          var list = res.data;
          for (var i = 0; i < list.length; i++) {
            var y = {};
            y.id = list[i].leader_id;
            y.name = list[i].leader_name;
            this.choosePerson.push(y);
          }

        }
      })
    }
  },

}
</script>
<style lang="scss" scoped>
::v-deep {
  .el-card{
    margin-bottom: 0;
    border: none;
    .el-card__body{
      padding-top: 0 !important;
    }
    .el-pagination {
      border: 1px solid #efefef;
      margin: 0;
      padding: 6px;
      border-top: none;
    }
  }
  .el-card__header{
    border: none;
  }
}
.select-meb-box{
  display: flex;
  padding: 20px;
  background-color: #f9fbfd;
  h4{
    padding: 0;
    margin: 4px;
    font-size: 14px;
    color: #666;
    font-weight: normal;
  }
}
</style>